﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CommonLibrary.Web.Core
{
    public class EntityRepositoryInMemory<T> : EntityRepository<T> where T : class
    {
        private int _nextId;
        protected IDictionary<int, object> _items;


        public EntityRepositoryInMemory()
        {
            _items = new Dictionary<int, object>();
        }


        /// <summary>
        /// Creates an item in the repository.
        /// </summary>
        /// <param name="item"></param>
        public override void Create(T item)
        {
            var id = this.CreateNextId();
            EntityHelper.SetId(item, id);
            _items[id] = item;
        }


        /// <summary>
        /// Gets an item from the repository by it's id.
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public override T Get(int id)
        {
            if (!_items.ContainsKey(id))
                return default(T);

            return (T)_items[id];
        }


        /// <summary>
        /// Deletes an item from the repository
        /// </summary>
        /// <param name="item"></param>
        public override void Delete(T item)
        {
            var id = this.GetId(item);
            _items.Remove(id);
        }


        /// <summary>
        /// Updates the item from the repository
        /// </summary>
        /// <param name="item"></param>
        public override void Update(T item)
        {
            var id = this.GetId(item);
            _items[id] = item;
        }


        /// <summary>
        /// Gets all the items from the repository.
        /// </summary>
        /// <returns></returns>
        public override List<T> GetAll()
        {
            var all = new List<T>();
            foreach (var pair in _items)
            {
                all.Add((T)pair.Value);
            }
            return all;
        }


        private int CreateNextId()
        {
            _nextId++;
            return _nextId;
        }
    }
}
